package com.dg.gaming.api.common.util
{

	import flash.display.BitmapData;
	import flash.display.Graphics;
	import flash.display.IBitmapDrawable;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.text.TextFieldAutoSize;

	import mx.core.UITextField;
	import mx.core.UITextFormat;
	import mx.graphics.ImageSnapshot;
	import mx.managers.ISystemManager;




	public class TextDraw
	{
		private var uiText:UITextField=new UITextField();
		private var uiTextFormet:UITextFormat;


		public function TextDraw(systemManager:ISystemManager, font:String=null, size:Object=null, color:Object=null, bold:Object=null, italic:Object=null, underline:Object=null, url:String=null, target:String=null, align:String=null, leftMargin:Object=null, rightMargin:Object=null, indent:Object=null, leading:Object=null)
		{
			uiTextFormet=new UITextFormat(systemManager, font, size, color, bold, italic, underline, url, target, align, leftMargin, rightMargin, indent, leading);
			uiText.setTextFormat(uiTextFormet);
			uiText.autoSize=TextFieldAutoSize.LEFT;
		}

		public function drawText(g:Graphics, x:int, y:int, text:String, center:Boolean=false):Point
		{
			uiText.text=text;
			uiText.setTextFormat(uiTextFormet);
			uiText.validateNow();
			return draw(g, x, y, uiText, center);
		}





		public function drawImage(g:Graphics, x:int, y:int, w:int, h:int, data:BitmapData, center:Boolean=false):void
		{
			var newData:BitmapData=new BitmapData(data.width, data.height, true);
			newData.draw(data);
			var scalex:Number=w / newData.width;
			var scaley:Number=h / newData.height;
			var scaleMatrix:Matrix=new Matrix();
			scaleMatrix.scale(scalex, scaley);
			var bitmap:BitmapData=new BitmapData(w, h, true);
			bitmap.draw(newData, scaleMatrix);
			var x1:int=(x + 0);
			var y1:int=(y + 0);
			if (center)
			{
				x1+=(w / 2);
				y1+=(h / 2);
			}

			var UIMatrix:Matrix=new Matrix();
			UIMatrix.tx=x1;
			UIMatrix.ty=y1;
			g.beginBitmapFill(bitmap, UIMatrix);
			g.lineStyle();
			g.drawRect(x1, y1, w, h);
			g.endFill();
		}





		private function draw(g:Graphics, x:int, y:int, source:IBitmapDrawable, center:Boolean=false):Point
		{
			var textBitmapData:BitmapData=ImageSnapshot.captureBitmapData(uiText);
			var sizeMatrix:Matrix=new Matrix();
			var coef:Number=Math.min(uiText.measuredWidth / textBitmapData.width, uiText.measuredHeight / textBitmapData.height);
			sizeMatrix.a=coef;
			sizeMatrix.d=coef;
			textBitmapData=ImageSnapshot.captureBitmapData(uiText, sizeMatrix);
			var sm:Matrix=new Matrix();
			var x1:int=(x + 0);
			var y1:int=(y + 0);
			if (center)
			{
				x1+=(uiText.width / 2);
				y1+=(uiText.height / 2);
			}
			sm.tx=x1;
			sm.ty=y1;
			g.beginBitmapFill(textBitmapData, sm);
			g.lineStyle();
			g.drawRect(x1, y1, uiText.width, uiText.height);
			g.endFill();
			return new Point(uiText.width, uiText.height);
		}

	}
}